const cloud = require('wx-server-sdk')

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})

const db = cloud.database()

exports.main = async (event, context) => {
  console.log('🔍 检查用户权限')
  
  try {
    const { OPENID } = cloud.getWXContext()
    const { permission, targetOpenid } = event
    
    if (!OPENID) {
      return {
        success: false,
        error: '用户身份验证失败'
      }
    }
    
    // 如果指定了目标用户，检查目标用户的权限
    const checkOpenid = targetOpenid || OPENID
    
    const result = await db.collection('user_permissions')
      .where({ openid: checkOpenid })
      .get()
    
    if (result.data.length === 0) {
      // 用户没有权限记录，只有基础权限
      return {
        success: true,
        data: {
          hasPermission: permission === 'basic',
          permissions: ['basic'],
          role: 'user',
          roleName: '普通用户'
        }
      }
    }
    
    const userPermissions = result.data[0]
    const hasPermission = userPermissions.permissions.includes(permission) || 
                         userPermissions.permissions.includes('super_admin')
    
    return {
      success: true,
      data: {
        hasPermission: hasPermission,
        permissions: userPermissions.permissions,
        role: userPermissions.role,
        roleName: userPermissions.roleName
      }
    }
    
  } catch (error) {
    console.error('❌ 检查用户权限失败:', error)
    return {
      success: false,
      error: error.message || '权限检查失败'
    }
  }
}
